﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sohar.Core
{
	public class Shuffler<T>
	{
		private T[] list;
		private int unavailableIndex;
		private Random random;

		public Shuffler(T[] array)
		{
			if (array.Length < 1)
				throw new ApplicationException("Array must have at least one item.");

			this.list = new T[array.Length];
			array.CopyTo(this.list, 0);
			this.random = new Random();
		}

		public T Next()
		{
			if (unavailableIndex == 0)
				unavailableIndex = list.Length;

			unavailableIndex--;

			int index = this.random.Next(0, unavailableIndex);
			T current = this.list[index];

			this.list[index] = this.list[unavailableIndex];
			this.list[unavailableIndex] = current;

			return current;
		}
	}
}
